<?php 

class Adept_Locator {

    protected $locations;
    protected $aliasFormat;

    public function __construct($locations, $aliasFormat = '*')
    {
        $this->locations = $locations;
        $this->aliasFormat = $aliasFormat;
    }

    public function locate($alias, $params = array())
    {
        $alias = $this->processAlias($alias);
        $paths = $this->locations;
        if (file_exists($alias)) {
            return $alias;
        }
        foreach ($paths as $path) {
            if (file_exists($path . '/' . $alias)) {
                return $path . '/' . $alias;
            }
        }
        $this->unresolvedAlias($alias);
        return false;
    }

    public function addLocation($location)
    {
        $this->locations[] = $location;
    }

    public function getFileLocations()
    {
        return $this->locations;
    }

    public function locateAll($prefix = '')
    {
        $result = array();
        $paths = $this->locations;
        foreach ($paths as $path) {
            if ($files = glob($path . $prefix . $this->aliasFormat)) {
                $result = array_merge($result, $files);
            }
        }
        return array_unique($result);
    }

    protected function processAlias($alias)
    {
        return str_replace('*', $alias, $this->aliasFormat);
    }

    protected function unresolvedAlias($alias)
    {
        throw new Adept_Exception("Cannot resolve alias", 0,
        array('alias' => $alias, 'locator' => get_class($this)));
    }

}